package com.th.control;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.th.bean.Category;
import com.th.bean.Dish;
import com.th.bean.DishFlavor;
import com.th.common.R;
import com.th.dto.DishDto;
import com.th.service.CategoryService;
import com.th.service.DishFlavorService;
import com.th.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;




    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);


        return R.success("添加菜品成功");
    }
//提示：这里拷贝的是分页信息，并非实体类属性！

  @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
      Page<Dish> dishPage = new Page<>(page, pageSize);
      Page<DishDto> dishDtoPage = new Page<>();

      LambdaQueryWrapper<Dish> dlw = new LambdaQueryWrapper<>();
      dlw.like(!StringUtils.isEmpty(name),Dish::getName,name);
      dlw.orderByDesc(Dish::getUpdateTime);

      dishService.page(dishPage,dlw);

      BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

      List<Dish> records = dishPage.getRecords();

      List<DishDto> dishDtoList=  records.stream().map((item)->{
          DishDto dishDto = new DishDto();
          BeanUtils.copyProperties(item,dishDto);
          Long categoryId = item.getCategoryId();
          Category category = categoryService.getById(categoryId);
          if(category != null){
              dishDto.setCategoryName(category.getName());
          }
          return dishDto;
      }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
  }

  @GetMapping("/{id}")
   public R<DishDto> updataList(@PathVariable Long id){
      DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
      return R.success(byIdWithFlavor);
  }

  @PutMapping()
    public R<String> updata(@RequestBody DishDto dishDto){
      System.out.println(dishDto);
      Long id = dishDto.getId();
      System.out.println(id);
      dishService.updateById(dishDto);

      LambdaQueryWrapper<DishFlavor> dlw = new LambdaQueryWrapper<>();
      dlw.eq(DishFlavor::getDishId,dishDto.getId());

      dishFlavorService.remove(dlw);

      List<DishFlavor> flavors = dishDto.getFlavors();
//      flavors.stream().map((item) -> {
//          item.setDishId(dishDto.getId());
//          return item;
//      }).collect(Collectors.toList());

      dishFlavorService.saveBatch(flavors);

      /**清理所有菜品缓存数据
       Set keys = redisTemplate.keys("dish_*");
       redisTemplate.delete(keys);  **/

      //清理某个分类下面的菜品缓存数据
      String key = "dish_"+dishDto.getCategoryId()+"1";
      redisTemplate.delete(key);

      return R.success("保存成功");
  }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        String key ="dish_"+dish.getCategoryId()+dish.getStatus();
        List<DishDto> dishDtoList=null;

        dishDtoList=  (List<DishDto>)redisTemplate.opsForValue().get(key);

        if(dishDtoList!=null){
          return   R.success(dishDtoList);
        }


        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件，查询状态为1的（起售状态）
        lambdaQueryWrapper.eq(Dish::getStatus, dish.getStatus());
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //条件排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);

         dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL: select* from dishflavor where dish_id=?;
            List<DishFlavor> dishFlavorlist = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorlist);
            return dishDto;
        }).collect(Collectors.toList());

       redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


}
